<template>
	<div class="log-list-container">
		<!-- 表格内容 -->
		<div class="logs-content" v-loading="loading">
			<!-- 空状态 -->
			<el-empty v-if="!loading && logsList.length === 0" :description="emptyDescription" :image-size="60" />
			<el-table v-else :data="logsList" stripe border :height="tableHeight" :size="tableSize" @row-click="showLogDetail" class="log-table">
				<el-table-column prop="task_name" label="任务名称" min-width="160" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-text :size="textSize">{{ scope.row.timerTask?.name || scope.row.task_name || '-' }}</el-text>
					</template>
				</el-table-column>

				<el-table-column prop="status" label="状态" width="80" align="center">
					<template #default="scope">
						<el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" :size="tagSize">
							{{ scope.row.status == 1 ? '成功' : '失败' }}
						</el-tag>
					</template>
				</el-table-column>

				<el-table-column prop="add_time" label="开始时间" min-width="160" align="center">
					<template #default="scope">
						<el-tooltip 
							:content="formatActualTime(scope.row.start_time)" 
							placement="top"
							:show-after="0"
						>
							<el-text :size="textSize">{{ formatTime(scope.row.start_time) }}</el-text>
						</el-tooltip>
					</template>
				</el-table-column>

				<el-table-column prop="exec_time" label="耗时" width="100" align="center">
					<template #default="scope">
						<el-text :size="textSize" type="info">{{ scope.row.exec_time }}ms</el-text>
					</template>
				</el-table-column>

				<el-table-column prop="exec_memory" label="内存" width="100" align="center" v-if="showMemory">
					<template #default="scope">
						<el-text :size="textSize" type="info">{{ formatMemory(scope.row.exec_memory) }}</el-text>
					</template>
				</el-table-column>

				<el-table-column label="操作提示" min-width="120" align="center" fixed="right">
					<template #default="scope">
						<el-text :size="textSize" type="info">点击查看详情</el-text>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 分页/加载更多 -->
		<div class="logs-footer row xy_center" v-if="showPagination">
			<el-pagination 
				v-model:current-page="pagination.page" 
				v-model:page-size="pagination.limit"
				:page-sizes="[10, 20, 50, 100]" 
				:total="pagination.total"
				layout="total, sizes, prev, pager, next" 
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange" 
				
			/>
		</div>
		<div class="logs-footer" v-else-if="hasMore">
			<el-button @click="loadMoreLogs" :loading="loadingMore" style="width: 100%;" type="primary" plain :size="buttonSize">
				加载更多日志
			</el-button>
		</div>
	</div>

	<!-- 日志详情组件 -->
	<LogDetail 
		v-model="detailVisible" 
		:log="selectedLog" 
		@close="detailVisible = false"
	/>
</template>

<script>
import { ElMessage } from 'element-plus'
import { formatFriendlyTime } from '../../../../utils/date'
import LogDetail from './logDetail.vue'

export default {
	name: 'LogList',
	components: {
		LogDetail
	},
	props: {
		// 任务ID，如果提供则获取特定任务日志，否则获取所有日志
		taskId: {
			type: [String, Number],
			default: null
		},
		// 表格高度
		tableHeight: {
			type: [String, Number],
			default: 300
		},
		// 是否显示操作列
		showActions: {
			type: Boolean,
			default: false
		},
		// 是否显示内存列
		showMemory: {
			type: Boolean,
			default: false
		},
		// 是否显示消息列
		showMessage: {
			type: Boolean,
			default: false
		},
		// 是否显示分页
		showPagination: {
			type: Boolean,
			default: false
		},
		// 每页条数
		pageSize: {
			type: Number,
			default: 20
		},
		// 表格大小
		size: {
			type: String,
			default: 'default',
			validator: (value) => ['large', 'default', 'small'].includes(value)
		}
	},
	data() {
		return {
			loading: false,
			loadingMore: false,
			logsList: [],
			hasMore: true,
			currentPage: 1,
			selectedLog: null,
			detailVisible: false,
			autoRefresh: false,
			refreshTimer: null,
			pagination: {
				page: 1,
				limit: 20,
				total: 0
			}
		}
	},
	computed: {
		// 空状态描述
		emptyDescription() {
			return this.taskId ? '暂无日志数据' : '暂无执行日志'
		},
		// 表格大小
		tableSize() {
			return this.size
		},
		// 文本大小
		textSize() {
			return this.size === 'large' ? 'default' : 'small'
		},
		// 标签大小
		tagSize() {
			return this.size === 'large' ? 'default' : 'small'
		},
		// 按钮大小
		buttonSize() {
			return this.size === 'large' ? 'default' : 'small'
		},
		
	},
	watch: {
		// 监听taskId变化，重新加载数据
		taskId(newVal, oldVal) {
			if (newVal !== oldVal) {
				this.loadLogs()
			}
		}
	},
	mounted() {
		// 设置分页大小
		this.pagination.limit = this.pageSize
		
		// 加载数据
		this.loadLogs()
		
		// 如果没有taskId（显示所有日志），开启自动刷新
		if (!this.taskId) {
			this.startAutoRefresh()
		}
	},
	unmounted() {
		this.stopAutoRefresh()
	},
	methods: {
		// 加载日志数据
		async loadLogs(isLoadMore = false, keepCurrentPage = false) {
			if (!isLoadMore) {
				this.loading = true
				if (this.showPagination) {
					// 分页模式：只有在不保持当前页码时才重置为第一页
					if (!keepCurrentPage) {
						this.pagination.page = 1
					}
				} else {
					this.currentPage = 1
					this.logsList = []
				}
			} else {
				this.loadingMore = true
			}
			
			try {
				const { getTaskLogs } = await import('../api')
				
				let params
				if (this.showPagination) {
					// 分页模式
					params = {
						page: this.pagination.page,
						limit: this.pagination.limit
					}
				} else {
					// 滚动加载模式
					params = {
						page: this.currentPage,
						limit: this.pageSize
					}
				}
				
				// 如果有taskId，添加筛选条件
				if (this.taskId) {
					params.where = { task_id: this.taskId }
				}
				
				const response = await getTaskLogs(params)
				
				if (response.code === 200) {
					const newLogs = response.data.list || []
					
					if (this.showPagination) {
						// 分页模式
						this.logsList = newLogs
						this.pagination.total = response.data.count || 0
					} else {
						// 滚动加载模式
						if (isLoadMore) {
							this.logsList.push(...newLogs)
						} else {
							this.logsList = newLogs
						}
						this.hasMore = newLogs.length === this.pageSize
						this.currentPage++
					}
				} else {
					throw new Error(response.message || '获取日志失败')
				}
			} catch (error) {
				ElMessage.error('获取日志失败: ' + error.message)
				if (!isLoadMore) {
					this.logsList = []
					if (this.showPagination) {
						this.pagination.total = 0
					}
				}
				this.hasMore = false
			} finally {
				this.loading = false
				this.loadingMore = false
			}
		},
		
		// 加载更多日志（仅滚动加载模式）
		loadMoreLogs() {
			if (!this.loadingMore && this.hasMore && !this.showPagination) {
				this.loadLogs(true)
			}
		},
		
		// 格式化友好时间显示
		formatTime(timeStr) {
			return formatFriendlyTime(timeStr)
		},
		
		// 格式化实际时间（用于tooltip显示）
		formatActualTime(timeStr) {
			if (!timeStr) return '--'
			try {
				const date = new Date(timeStr.replace(/[：]/g, ':'))
				if (isNaN(date.getTime())) {
					return timeStr
				}
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit'
				})
			} catch (e) {
				return timeStr
			}
		},
		
		// 格式化内存使用
		formatMemory(bytes) {
			if (!bytes || bytes === 0) return '0 B'
			const k = 1024
			const sizes = ['B', 'KB', 'MB', 'GB']
			const i = Math.floor(Math.log(bytes) / Math.log(k))
			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
		},
		
		// 显示日志详情
		showLogDetail(log) {
			this.selectedLog = log
			this.detailVisible = true
		},
		
		// 分页处理
		handleSizeChange(newSize) {
			this.pagination.limit = newSize
			this.pagination.page = 1
			this.loadLogs(false, false) // 改变页面大小时重置到第一页
		},
		
		handleCurrentChange(newPage) {
			this.pagination.page = newPage
			this.loadLogs(false, true) // 翻页时保持当前页码
		},

		// 开始自动刷新（仅显示所有日志时）
		startAutoRefresh() {
			if (!this.taskId) {
				this.autoRefresh = true
				this.refreshTimer = setInterval(() => {
					if (this.autoRefresh && !this.loading) {
						// 分页模式保持当前页，滚动模式重置到第一页
						this.loadLogs(false, this.showPagination)
					}
				}, 30000) // 每30秒刷新一次
			}
		},
		
		// 停止自动刷新
		stopAutoRefresh() {
			this.autoRefresh = false
			if (this.refreshTimer) {
				clearInterval(this.refreshTimer)
				this.refreshTimer = null
			}
		}
	}
}
</script>

<style scoped>
.log-list-container {
	height: 100%;
	display: flex;
	flex-direction: column;
}

.logs-content {
	flex: 1;
	margin-bottom: 12px;
}

.logs-footer {
	padding: 12px 0;
	border-top: 1px solid var(--el-border-color-lighter);
}

/* 表格行可点击样式 */
.log-table :deep(.el-table__row) {
	cursor: pointer;
	transition: background-color 0.2s;
}

.log-table :deep(.el-table__row:hover) {
	background-color: var(--el-color-primary-light-9) !important;
}
</style> 